package com.mango.community.controller;

import com.alibaba.fastjson.JSONObject;
import com.mango.community.entity.Message;
import com.mango.community.entity.Page;
import com.mango.community.entity.User;
import com.mango.community.service.MessageService;
import com.mango.community.service.UserService;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.CommunityUtil;
import com.mango.community.util.HostHolder;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.jws.soap.SOAPBinding;
import java.util.*;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/8/5 22:14
 */
@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;

    /** 查询私信列表
     * @param model
     * @param page
     * @return
     */
    @GetMapping("/letter/list")
    public String getLetterList(Model model , Page page){
        //获取用户信息
        User user = hostHolder.getUser();
        //设置分页的信息
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));
        //查询会话列表
        List<Message> conversationList = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String,Object>> conversations = new ArrayList<>();
        //conversationList 判断空值
        if(conversationList != null){
            //遍历conversationList
            for (Message message : conversationList) {
                //将每次遍历出来的数据放入到map中
                Map<String,Object> map = new HashMap<>();
                map.put("conversation",message);
                //查询当前会话全部私信的数量，放入map
                map.put("letterCount",messageService.findLetterCount(message.getConversationId()));
                //查询当前会话未读私信的数量，放入map
                map.put("unreadCount",messageService.findLetterUnreadCount(user.getId(),message.getConversationId()));
                //判断当前的对象是私信的发起者还是接受者
                int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
                //将私信发起者的信息放入map
                map.put("target",userService.findUserById(targetId));
                //将map放入到list集合中
                conversations.add(map);
            }
        }
        //放入model中返回给前台
        model.addAttribute("conversations",conversations);
        //查询全部未读私信数量
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        //查询全部未读通知数量
        int noticeUnreadCount = messageService.findNoticeUnreadCount(hostHolder.getUser().getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId,Page page ,Model model){
        //设置分页信息
        page.setLimit(5);
        page.setPath("/letter/detail"+conversationId);
        page.setRows(messageService.findLetterCount(conversationId));
        //私信列表
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String,Object>> letters = new ArrayList<>();
        //判断空值
        if( letterList != null){
            //遍历letterList
            for (Message message : letterList) {
                Map<String,Object> map = new HashMap<>();
                //将私信信息放入map
                map.put("letter",message);
                //将私信的发起人放入map
                map.put("fromUser",userService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        model.addAttribute("letters",letters);
        //查询私信的目标
        model.addAttribute("target",getLetterTarget(conversationId));
        //将未读的消息设置为已读
        List<Integer> ids = getLetterIds(letterList);
        //判断ids不为空
        if(!ids.isEmpty()){
            //执行将消息的状态修改为已读状态
            messageService.readMessage(ids);
        }

        return "site/letter-detail";
    }

    /** 通过会话id 获取私信发起人的信息
     * @param conversationId
     * @return
     */
    private User getLetterTarget(String conversationId){
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);
        if(hostHolder.getUser().getId() == id0){
            return userService.findUserById(id1);
        }else {
            return userService.findUserById(id0);
        }
    }

    /** 获取未读消息id的集合
     * @param letterList letterList 消息的集合
     * @return
     */
    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> ids = new ArrayList<>();
        //判断消息集合是否为空
        if(letterList != null){
            //遍历消息集合
            for (Message message : letterList) {
                //判断当前用户的身份，只有是消息的接收者的身份才有已读未读的情况 并且消息的状态是0（未读）
                if(hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0){
                    //将消息的id放入到未读消息的集合中
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    /** 发送私信
     * @param toName  发送给谁
     * @param content  发送的消息
     * @return
     */
    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName,String content){
        //根据消息接受者的名字查询出用户的信息
        User target = userService.findUserByName(toName);
        //判断用户信息是否为空
        if(target == null){
            //为空直接返回并且提示
            return CommunityUtil.getJSONString(1,"目标用户不存在");
        }
        //给message对象设置值
        Message message = new Message();
        //设置消息的发送者，从当前登录的对象中获取
        message.setFromId(hostHolder.getUser().getId());
        //设置消息的接收者,从上面查询到的user对象中获取
        message.setToId(target.getId());
        //根据ConversationId的规则来设置,判断fromId 和toId的大小来设置值
        if(message.getFromId() <message.getToId()){
            message.setConversationId(message.getFromId()+"_"+message.getToId());
        }else{
            message.setConversationId(message.getToId()+"_"+message.getFromId());
        }
        //status 因为默认值就是0 就是未读状态，所以可以不用设置
        //设置消息的内容
        message.setContent(content);
        //设置消息的创建时间
        message.setCreateTime(new Date());
        //执行新增方法
        messageService.addMessage(message);
        //给页面返回状态，0 就是代表成功
        return CommunityUtil.getJSONString(0);
    }

    /** 查询通知信息
     * @param model
     * @return
     */
    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        //查询评论的通知
        User user = hostHolder.getUser();
        Message message = messageService.findLatestNotice(user.getId(),TOPIC_COMMENT);
        //因为页面要的数据比这个查询出来的数据多，所以需要进一步的封装
        Map<String ,Object>  messageVO = new HashMap<>();
        if(message != null ){
            messageVO.put("message",message);
            //将数据库中数据的转义字符去掉
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //将得到的content转为java的map对象，存的时候用的是什么现在就用什么
            HashMap data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user",userService.findUserById((Integer)data.get("userId")));
            messageVO.put("entityType",data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));
            //查询通知的数量
            int count = messageService.findNoticeCount(user.getId(),TOPIC_COMMENT);
            messageVO.put("count",count);
            //查询通知的未读数量
            int unRead = messageService.findNoticeUnreadCount(user.getId(),TOPIC_COMMENT);
            messageVO.put("unRead",unRead);
        }
        model.addAttribute("commentNotice",messageVO);
        //查询点赞的通知
        message = messageService.findLatestNotice(user.getId(),TOPIC_LIKE);
        //因为页面要的数据比这个查询出来的数据多，所以需要进一步的封装
        messageVO = new HashMap<>();
        if(message != null ){
            messageVO.put("message",message);
            //将数据库中数据的转义字符去掉
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //将得到的content转为java的map对象，存的时候用的是什么现在就用什么
            HashMap data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user",userService.findUserById((Integer)data.get("userId")));
            messageVO.put("entityType",data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            messageVO.put("postId",data.get("postId"));
            //查询通知的数量
            int count = messageService.findNoticeCount(user.getId(),TOPIC_LIKE);
            messageVO.put("count",count);
            //查询通知的未读数量
            int unRead = messageService.findNoticeUnreadCount(user.getId(),TOPIC_LIKE);
            messageVO.put("unRead",unRead);
        }
        model.addAttribute("likeNotice",messageVO);
        //查询关注的通知
        message = messageService.findLatestNotice(user.getId(),TOPIC_FOLLOW);
        //因为页面要的数据比这个查询出来的数据多，所以需要进一步的封装
        messageVO = new HashMap<>();
        if(message != null ){
            messageVO.put("message",message);
            //将数据库中数据的转义字符去掉
            String content = HtmlUtils.htmlUnescape(message.getContent());
            //将得到的content转为java的map对象，存的时候用的是什么现在就用什么
            HashMap data = JSONObject.parseObject(content, HashMap.class);
            messageVO.put("user",userService.findUserById((Integer)data.get("userId")));
            messageVO.put("entityType",data.get("entityType"));
            messageVO.put("entityId",data.get("entityId"));
            //查询通知的数量
            int count = messageService.findNoticeCount(user.getId(),TOPIC_FOLLOW);
            messageVO.put("count",count);
            //查询通知的未读数量
            int unRead = messageService.findNoticeUnreadCount(user.getId(),TOPIC_FOLLOW);
            messageVO.put("unRead",unRead);
        }
        model.addAttribute("followNotice",messageVO);
        //查询未读消息数量
        //私信
        int letterUnreadCount = messageService.findLetterUnreadCount(hostHolder.getUser().getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        //通知
        int noticeUnreadCount = messageService.findNoticeUnreadCount(hostHolder.getUser().getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/notice";
    }

    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page , Model model){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/notice/detail/"+topic);
        page.setRows(messageService.findNoticeCount(user.getId(),topic));
        //获取该主题下的通知列表
        List<Message> noticeList = messageService.findNotices(user.getId(),topic,page.getOffset(),page.getLimit());
        List<Map<String,Object>> noticeVOList = new ArrayList<>();
        if(noticeList != null ){
            for (Message notice : noticeList) {
                Map<String,Object> map = new HashMap<>();
                //通知
                map.put("notice",notice);
                //内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String,Object> data = JSONObject.parseObject(content,HashMap.class);
                map.put("user",userService.findUserById((Integer)data.get("userId")));
                map.put("entityType",data.get("entityType"));
                map.put("entityId",data.get("entityId"));
                map.put("postId",data.get("postId"));
                //通知的作者，系统用户
                map.put("fromUser",userService.findUserById(notice.getFromId()));
                noticeVOList.add(map);
            }
        }
        model.addAttribute("notices",noticeVOList);
        //设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if(ids.size() !=0 ){
            messageService.readMessage(ids);
        }
        return "/site/notice-detail";
    }
}
